package org.example.thread;

import java.util.ArrayList;
import java.util.List;

public class Demo6 {

    private List<Object> store = new ArrayList<>();

    public synchronized void produce() {
        while(true){
            if(store.size()==0){
                for (int i = 0; i < 10; i++) {
                    try {
                        System.out.println("生产商品:" + i);
                        store.add("商品"+i);
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                System.out.println("生产结束, 通知消费方法!");
                try {
                    // 通知其他等待的线程
                    this.notify();
                    // 进入等待状态
                    this.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    public void consume() {
        while(true){
            synchronized (this){
                while(store.size()!=0){
                    Object good = store.remove(0);
                    System.out.println("-------消费商品: "+good);
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                System.out.println("-------商品消费完成, 通知生产");
                this.notify();
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }

    public static void main(String[] args) {
        Demo6 demo = new Demo6();
        new Thread(()->demo.produce()).start();
        new Thread(demo::consume).start();
    }


}
